﻿<ServiceBehavior(ConcurrencyMode:=ConcurrencyMode.Multiple, InstanceContextMode:=InstanceContextMode.Single)> _
Public Class WebServer
    Implements Web

    Dim GameServer As GameServer

    Sub New(ByVal GameServer As GameServer)
        Me.GameServer = GameServer
    End Sub

    Public Function HomePage() As IO.Stream Implements Web.HomePage
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"

        Dim MS As IO.Stream = DirectCast(New IO.FileStream("WebResources\SilverlightHomePage.html", IO.FileMode.Open), IO.Stream)

        MS.Position = 0
        Return MS
    End Function

    Public Function NonSilverlightHomePage() As IO.Stream Implements Web.NonSilverlightHomePage
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"

        Dim MS As New IO.MemoryStream
        Dim SW As New IO.StreamWriter(MS)
        Dim HTML As String = (New IO.StreamReader("WebResources\HomePage.html", IO.FileMode.Open)).ReadToEnd

        HTML = HTML.Replace("$gamesrunning$", GameServer.Games.Count)

        Dim GamesTable As String = "<table border=1><tr><td>Game Name</td><td>Total Users</td></tr>"

        For Each Game As Game In GameServer.Games.Values
            GamesTable += "<tr>"
            GamesTable += "<td><a href=GetDetails?Game=" & Game.Name.Replace(" ", "%20") & ">" & Game.Name & "</a>" & "</td>" & "<td>" & Game.Scores.Count & "</td>"
            GamesTable += "</tr>"
        Next

        GamesTable += "</table>"

        HTML = HTML.Replace("$gamestable$", GamesTable)

        SW.Write(HTML)
        SW.Flush()

        MS.Position = 0
        Return MS
    End Function

    Public Function GetResource(ByVal Resource As String) As IO.Stream Implements Web.GetResource
        Try
            If Resource = "" Then
                Dim MS As New IO.MemoryStream
                Dim SW As New IO.StreamWriter(MS)

                SW.Write("Virtual Directory browsing is not allowed")
                SW.Flush()

                MS.Position = 0
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"
                Return MS
            End If
            Resource = Resource.Replace(""""c, "")
            Dim stream As IO.Stream = DirectCast(New IO.FileStream("WebResources\" & Resource, IO.FileMode.Open), IO.Stream)

            'Set the correct context type for the file requested.
            Dim extIndex As Integer = Resource.LastIndexOf(".")
            Dim extension As String = Resource.Substring(extIndex, Resource.Length - extIndex)
            Select Case extension
                Case ".jpg", ".jpeg"
                    WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpg"
                Case ".gif"
                    WebOperationContext.Current.OutgoingResponse.ContentType = "image/gif"
                Case ".ico"
                    WebOperationContext.Current.OutgoingResponse.ContentType = "image/ico"
                Case ".xbap"
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-ms-xbap"
                Case ".html"
                    WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"
                Case Else
                    'Throw (New ApplicationException("File type not supported"))
            End Select
            Return stream
        Catch
            Try
                Dim _Game As Game
                _Game = GameServer.Games(GameServer.GameNames(Resource.Replace("Image.img", "")))
                Dim MS As New IO.MemoryStream(Convert.FromBase64String(_Game.CurrentQuestion.Image))
                Dim Image As Drawing.Image = Drawing.Image.FromStream(MS)
                Dim MS2 As New IO.MemoryStream()
                Image.Save(MS2, Drawing.Imaging.ImageFormat.Png)
                MS2.Position = 0

                WebOperationContext.Current.OutgoingResponse.ContentType = "image/png"

                Return MS2
            Catch
                Dim MS As New IO.MemoryStream
                Dim SW As New IO.StreamWriter(MS)

                SW.Write("Resource not found.")
                SW.Flush()

                MS.Position = 0
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"
                Return MS
            End Try
        End Try
    End Function

    Public Function DownloadFile(ByVal File As String) As IO.Stream Implements Web.DownloadFile
        Try
            Dim MS As IO.Stream = DirectCast(New IO.FileStream("Download\" & File, IO.FileMode.Open), IO.Stream)
            MS.Position = 0
            Return MS
        Catch ex As Exception
            WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"
            Dim MS As New IO.MemoryStream
            Dim SW As New IO.StreamWriter(MS)
            Dim HTML As String

            HTML = "<HTML><body><p>Error Downloading file: </p><p>" & ex.Message & "</p></body></HTML>"

            SW.Write(HTML)
            SW.Flush()

            MS.Position = 0
            Return MS
        End Try
    End Function

    Public Function GetDetails(ByVal Game As String) As System.IO.Stream Implements Web.GetDetails
        Dim MS As New IO.MemoryStream
        Dim SW As New IO.StreamWriter(MS)
        Dim _Game As Game

        Try
            _Game = GameServer.Games(GameServer.GameNames(Game))
        Catch
            SW.WriteLine("Game not found. Click <a href=HomePage>Here</a> to return to the homepage")
            GoTo ReturnLine
        End Try

        Dim HTML As String = (New IO.StreamReader("WebResources\DetailPage.html", IO.FileMode.Open)).ReadToEnd

        HTML = HTML.Replace("$title$", "Game Details: " & Game)

        Dim GamesTable As String = "<table width=100% border=1><colgroup align=center><col width=200><col><col width=200><tr><td width = 50>Scoreboard</td><td>Current Question</td><td width = 50>Question Image</td></tr>"

        GamesTable += "<tr><td><table width=100% border=1><tr><td>User Name</td><td>Score</td></tr>"
        For Each Score In _Game.Scores
            GamesTable += "<tr><td>" & Score.Key & "</td><td>" & Score.Value & "</td></tr>"
        Next
        GamesTable += "</table></td>"
        If Not _Game.CurrentQuestion Is Nothing Then
            With _Game.CurrentQuestion
                If .IsIsMultichoiceNull = False Then
                    If .IsMultichoice = False Then
                        GamesTable += "<td>" & .QuestionText & "</td>"
                    Else
                        GamesTable += "<td><p>" & .QuestionText & "</p><p>A: " & .A & " B: " & .B & " C: " & .C & " D: " & .D & "</p></td>"
                    End If
                Else
                    GamesTable += "<td>" & .QuestionText & "</td>"
                End If
                If .IsImageNull = False Then
                    GamesTable += "<td><center><img width = 150 height = 150 alt=" & """"c & "Question Image" & """"c & "src=" & """"c & "WebResources/" & Game.Replace(" ", "%20") & "Image.img" & """"c & "/></center></td>"
                End If
            End With
        End If
        GamesTable += "</tr></table>"

        HTML = HTML.Replace("$detail$", GamesTable)

        SW.Write(HTML)

ReturnLine:
        SW.Flush()

        MS.Position = 0
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"
        Return MS
    End Function
End Class

<ServiceContract()> _
Public Interface Web

    <OperationContract(name:="*")> _
    <WebGet()> _
    Function HomePage() As IO.Stream

    <OperationContract()> _
    <WebGet()>
    Function NonSilverlightHomePage() As IO.Stream

    <OperationContract()> _
    <WebGet(UriTemplate:="/WebResources/{*Resource}")> _
    Function GetResource(ByVal Resource As String) As IO.Stream

    <OperationContract()> _
    <WebGet(UriTemplate:="/Download/{*File}")> _
    Function DownloadFile(ByVal File As String) As IO.Stream

    <OperationContract()> _
    <WebGet()> _
    Function GetDetails(ByVal Game As String) As IO.Stream

End Interface